package com.shang.controller;

import com.alibaba.fastjson.JSON;
import com.shang.common.CommonResult;
import com.shang.common.ErrorCode;
import com.shang.dto.*;
import com.shang.entity.User;
import com.shang.service.UserService;
import com.shang.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@EnableSwagger2
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping(value = "/getTokenByUser", method = RequestMethod.POST)
    @ApiOperation(value = "getTokenByUser", notes = "根据用户名称获取token")
    public CommonResult getTokenByUser(@RequestBody LoginDTO loginDTO) {
        CommonResult commonResult = new CommonResult();
        Token tokenObj = new Token();
        String collectionName = "user";
        try {
            String userName = loginDTO.getUserName();
            String password = loginDTO.getPassword();
            Criteria criteria = Criteria.where("userName").is(userName);
            User user = mongoTemplate.findOne(new Query(criteria), User.class, collectionName);
            if (!user.getPassword().equals(password)) {
                return commonResult.fail(ErrorCode.PASSWORD_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
            }
            String token = JWTUtils.createToken(user.getUserName());
            redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(user), 1, TimeUnit.DAYS);
            tokenObj.setToken(token);
            return commonResult.success(tokenObj);
        } catch (Exception e) {
            e.printStackTrace();
            return commonResult.fail(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SESSION_TIME_OUT.getMsg());
        }
    }
//        String collectionName="user";
//        String userName=loginDTO.getUserName();
//        Criteria criteria=Criteria.where("userName").is(userName);
//        User user=mongoTemplate.findOne(new Query(criteria),User.class,collectionName);
//        String password = user.getPassword();
//        log.info(password);
//        String token= JWTUtils.createToken();
//        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1,TimeUnit.DAYS);
//        return CommonResult.success(token);
//    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ApiOperation(value = "addUser", notes = "注册新用户")
    public CommonResult addUser(@RequestBody UserAddDTO userAddDTO) {
        CommonResult commonResult = new CommonResult();
        try {
            String collectionName = "user";
            User user = new User();
            user.setUserName(userAddDTO.getUserName());
            user.setPassword(userAddDTO.getPassword());
            user.setTelephone(userAddDTO.getTelephone());
            user.setRole(userAddDTO.getRole()); //默认为普通用户 0：管理员 1：普通用户
            user.setAvatar(""); //默认没有头像
            User userAdd = mongoTemplate.insert(user, collectionName);
            log.info("成功添加用户" + userAdd);
        } catch (Exception e) {
            e.printStackTrace();
            return commonResult.fail(ErrorCode.ACCOUNT_EXIT.getCode(), ErrorCode.ACCOUNT_EXIT.getMsg());
        }
        return commonResult.success();
    }

    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    @ApiOperation(value = "getUsers", notes = "获取所有用户")
    public CommonResult getUsers(@RequestParam int limit) {
        CommonResult commonResult = new CommonResult();
        String collectionName = "user";
        Query query = new Query().limit(limit);
        List<User> users = mongoTemplate.find(query, User.class, collectionName);
        return commonResult.success(users);
    }

    @RequestMapping(value = "/getUsersByPage", method = RequestMethod.GET)
    @ApiOperation(value = "getUsersByPage", notes = "分页获取用户列表")
    public CommonResult getUsersByPage(@RequestParam int pageNum,int pageSize) {
        CommonResult commonResult = new CommonResult();
        try {
            if (pageNum < 0 || pageSize < 0) {
                return commonResult.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
            }
            List<UserLookDTO> userList = userService.getUsersByPage(pageNum, pageSize);
            if (userList.size()==0){
                return commonResult.fail("没有数据了");
            }
            commonResult=CommonResult.success(userList);
        } catch (Exception e) {
            return commonResult.fail(e.toString());
        }
        return commonResult;
    }

    @RequestMapping(value = "/getUserNumber",method = RequestMethod.GET)
    @ApiOperation(value = "getUserNumber",notes = "获取用户数量")
    public CommonResult getUserNumber(){
        CommonResult commonResult=new CommonResult();
        try {
            int userNumber = userService.getUserNumber();
            commonResult=CommonResult.success(userNumber);
        }catch (Exception e){
            return commonResult.fail(e.toString());
        }
        return commonResult;
    }

    @RequestMapping(value = "/deleteUserByName",method = RequestMethod.GET)
    @ApiOperation(value = "deleteUserByName",notes = "根据名称删除用户")
    public CommonResult deleteUserByName(@RequestParam String userName){
        CommonResult commonResult=new CommonResult();
        try {
            int userNumber = userService.deleteUserByName(userName);
            commonResult=CommonResult.success(userNumber);
        }catch (Exception e){
            return commonResult.fail(e.toString());
        }
        return commonResult;
    }
    @RequestMapping(value = "/getUserByName",method = RequestMethod.GET)
    @ApiOperation(value = "getUserByName",notes = "根据名称查找用户")
    public CommonResult getUserByName(@RequestParam String userName){
        CommonResult commonResult=new CommonResult();
        try {
            List<User> userByName = userService.getUserByName(userName);
            if (userByName.size()==0){
                return commonResult.fail("未找到此用户");
            }
            else commonResult=CommonResult.success(userByName);
        }catch (Exception e){
            return commonResult.fail(e.toString());
        }
        return commonResult;
    }
}